Url  = require "url"
Path = require "path"
ScopedClient = require "scoped-http-client"
###########################################################################
class JenkinsApi
  constructor: (@userToken, @application) ->
    @token = @apiToken()

    @parsedApiUrl = Url.parse(@apiUri())
    @hostname     = @parsedApiUrl.host

  apiUri: ->
    (@application? and @application['jenkins_api']) or
      process.env.HUBOT_JENKINS_API

  apiToken: ->
    (@application? and @application['jenkins_token']) or
      (@userToken? and @userToken) or
      process.env.HUBOT_JENKINS_TOKEN

  filterPaths: ->
    newArr = @pathParts().filter (word) -> word isnt ""

  pathParts: ->
    @parsedApiUrl.path.split("/")

  path: (suffix) ->
    if suffix?.length > 0
      parts = @filterPaths()
      parts.push(suffix)
      "/#{parts.join('/')}"
    else
      @parsedApiUrl.path

  client: ->
    ScopedClient.create("http://#{@hostname}").
      header("User-Agent", "hubot-jenkins-deploy-v0.1").
      header("Authorization", "Basic #{@userToken}")

exports.Api              = JenkinsApi
exports.Deployment       = require(Path.join(__dirname, "api", "deployment")).Deployment
